package com.now.printer.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;

import com.now.printer.R;
import com.now.printer.base.BaseActivity2;
import com.now.printer.utils.FileUtils;
import com.now.printer.utils.PrinterUtils;
import com.uttampanchasara.pdfgenerator.CreatePdf;
import com.xuexiang.xutil.net.NetworkUtils;

import org.jetbrains.annotations.NotNull;
import org.xutils.common.util.LogUtil;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;

public class WebViewActivity extends BaseActivity2 implements View.OnClickListener {

    public static final String INTENT_KEY_URL = "INTENT_KEY_URL";
    public static final String INTENT_KEY_TITLE = "INTENT_KEY_TITLE";

    private WebView webView;

    private String title;
    private TextView tv_print;

    private EditText et_url;
    String newUrl = "";

    @Override
    public int getLayoutId() {
        return R.layout.activity_web_view;
    }

    @Override
    public void doBusiness(Context mContext) {

        tv_print = findViewById(R.id.tv_print);
        tv_print.setOnClickListener(this);
        String url = getIntent().getStringExtra(INTENT_KEY_URL);
        title = getIntent().getStringExtra(INTENT_KEY_TITLE);

        if (TextUtils.isEmpty(url)){
            url = "http://www.baicu.com";
        }
        if (url.startsWith("http://") || url.startsWith("https://")) {
            newUrl = url;
        } else {
            newUrl = "http://" + url;
        }
        LogUtil.i("url 是：" + newUrl);
        et_url = findViewById(R.id.et_url);
        et_url.setHint("" + newUrl);
        et_url.setFocusable(false);
        webView = findViewById(R.id.webView);
        webView.loadUrl(newUrl);
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);//当网页加载提示无法打开的时候， 这里生效
        //支持插件
//        webSettings.setPluginsEnabled(true);
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
//缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
//其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                    return false;
                } else {
//                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//                    startActivity(intent);
                    return true;
                }
            }
        });

        if (!NetworkUtils.isAvailableByPing()) {
            tv_print.setText("暂不支持打印");
            tv_print.setClickable(false);
            return;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

//    public static boolean isAppExist(Context context, String packageName) {
//        if (!TextUtils.isEmpty(packageName)) {
//            PackageManager manager = context.getPackageManager();
//            List<PackageInfo> list = manager.getInstalledPackages(0);
//            for (PackageInfo info : list) {
//                if (packageName.equalsIgnoreCase(info.packageName)) {
//                    return true;
//                }
//            }
//        }
//        return false;
//    }

    @Override
    protected void onDestroy() {
        //清除网页访问留下的缓存
        //由于内核缓存是全局的因此这个方法不仅仅针对webview而是针对整个应用程序.
        webView.clearCache(true);
        //清除当前webview访问的历史记录
        //只会webview访问历史记录里的所有记录除了当前访问记录
        webView.clearHistory();
        //这个api仅仅清除自动完成填充的表单数据，并不会清除WebView存储到本地的数据
        webView.clearFormData();
        super.onDestroy();
    }

    private boolean isFirst = true;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_print:


                LogUtil.i("当前url是：" + webView.getUrl());
                LogUtil.i("当前 OriginalUrl是：" + webView.getOriginalUrl());
                String appPath = FileUtils.getCurrentAppPath(this);

                File file = new File(appPath + File.separator + "printer_html.pdf");
                if (file.exists()) {
                    file.delete();
                    LogUtil.i("删除成功");
                }
                new CreatePdf(WebViewActivity.this)
                        .setPdfName("printer_html")
                        .openPrintDialog(false)
                        .setContentBaseUrl(webView.getUrl())
                        .setPageSize(PrintAttributes.MediaSize.ISO_A4)
                        .setContent(getHtmlLink(webView.getUrl()))
                        .setFilePath(appPath)
                        .setCallbackListener(new CreatePdf.PdfCallbackListener() {
                            @Override
                            public void onFailure(@NotNull String s) {
                                // handle error
                                LogUtil.i("onFailure：" + s);

                            }

                            @Override
                            public void onSuccess(@NotNull String filePath) {
                                // do your stuff here
                                if (isFirst) {
                                    isFirst = false;
                                    LogUtil.i("onSuccess：" + filePath);

                                    new Handler().postDelayed(new Runnable() {
                                        public void run() {
                                            //显示dialog
                                            PrinterUtils.doPrint(WebViewActivity.this, filePath);

                                        }
                                    }, 2000);   //5秒
                                }
                            }
                        })
                        .create();
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        isFirst = true;
    }

    private String getHtmlLink(String htmlUrl) {
        /*rel="stylesheet" */
        String head = "<head>\n" +
                "    <meta charset=\"utf-8\" />\n" +
                "    <title>主页面</title>\n" +
                "    <link href=" + htmlUrl + "id=\"page1\"/>\n"
//                "    <link rel=\"import\" href=\"fotter.html\" id=\"page2\"/>\n" +
                + "<script type=\"text/javascript\">window.location.href=\"" + htmlUrl + "\";</script>" +  "</head>";

        return "<html>" + head + "<body></body></html>";
    }

    /**
     * 加载html标签
     *
     * @param bodyHTML
     * @return
     */
    private String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>img{max-width: 100%; width:auto; height:auto!important;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }
}